package menu

import (
	"context"
	"go-zero-project/common/ctxdata"
	"go-zero-project/services/user/api/internal/svc"
	"go-zero-project/services/user/api/internal/types"
	"go-zero-project/services/user/rpc/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type NavigationLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewNavigationLogic(ctx context.Context, svcCtx *svc.ServiceContext) *NavigationLogic {
	return &NavigationLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *NavigationLogic) Navigation() (resp *types.NavListResp, err error) {
	// 1.builder rpc request
	// 1.1 token 里面获取userId
	uidFromCtx := ctxdata.GetUidFromCtx(l.ctx)
	navReq := pb.NavListReq{UserId: uidFromCtx}
	// 2.request rpc
	navListResp, err := l.svcCtx.UserCenterClient.NavList(l.ctx, &navReq)
	if err != nil {
		return nil, err
	}
	// 3.return obj
	menuArr := navListResp.MenuArr
	var navArr []types.MenuInfoResp
	if len(menuArr) == 0 {
		return &types.NavListResp{MenuArr: navArr}, err
	}
	return &types.NavListResp{MenuArr: l.loopMenuArr(menuArr)}, err

}

// loopMenuArr 递归封装参数
func (l *NavigationLogic) loopMenuArr(menuArr []*pb.MenuInfoResp) []types.MenuInfoResp {
	var navArr []types.MenuInfoResp
	for i := 0; i < len(menuArr); i++ {
		infoResp := types.MenuInfoResp{
			MenuId:   menuArr[i].MenuId,
			ParentId: menuArr[i].ParentId,
			Name:     menuArr[i].Name,
			Url:      menuArr[i].Url,
			Perms:    menuArr[i].Perms,
			MenuType: int(menuArr[i].MenuType),
			Icon:     menuArr[i].Icon,
			OrderNum: int(menuArr[i].OrderNum),
		}
		list := menuArr[i].List
		if len(list) > 0 {
			menuInArr := l.loopMenuArr(list)
			infoResp.List = menuInArr
		}
		navArr = append(navArr, infoResp)
	}
	return navArr
}
